package weekMatch.one_339;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeeCode_03 {
    public static void main(String[] args) {
        System.out.println(minOperations(new int[]{3, 1, 6, 8}, new int[]{1, 5}));
        System.out.println(minOperations(new int[]{2,9,6,3}, new int[]{10}));
    }
    private static List<Long> minOperations(int[] nums, int[] queries) {
        List<Long> ans = new ArrayList<>();
        Arrays.sort(nums);
        long[] sums = new long[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            sums[i + 1] = nums[i] + sums[i];
        }
        for (int query : queries) {
            int j = getCount(nums, query);
            ans.add((long) j * query - sums[j] + sums[nums.length] - sums[j] - (long) (nums.length - j) * query);
        }
        return ans;
    }
    private static int getCount(int[] nums, int goal){
        int l = -1;
        int r = nums.length;
        while (l + 1 < r){
            int m = l + (r - l) / 2;
            if (nums[m] < goal){
                l = m ;
            }else {
                r = m;
            }
        }
        return r;
    }
}
